<template>
	<uv-upload :fileList="fileList" name="fileUpload" multiple :maxCount="10" @afterRead="afterRead"
		@delete="deletePic"></uv-upload>
</template>

<script setup>
	import {
		ref,
		watch,
		onMounted
	} from 'vue';

	const props = defineProps({
		initialFiles: {
			type: [Array, Promise],
			default: () => []
		}
	})
	// 文件列表
	const fileList = ref([]);
	const emit = defineEmits(['file-change', 'upload-complete', 'delete-file'])
	// 删除图片
	const deletePic = (event) => {
		console.log("删除了", event)
		fileList.value.splice(event.index, 1);
		emit('delete-file', {
			index: event.index,
			file: event.file,
			remainingFiles: [...fileList.value]
		})
	};

	// 新增图片
	const afterRead = async (event) => {
		try {
			// 统一处理单文件和多个文件的情况
			const files = Array.isArray(event.file) ? event.file : [event.file];
			const startIndex = fileList.value.length;

			// 准备上传文件列表（浅拷贝避免污染原始数据）
			const uploadingFiles = files.map(file => ({
				...file,
				status: 'uploading',
				message: '上传中'
			}));

			// 批量添加到文件列表
			fileList.value.push(...uploadingFiles);
			emit('file-change', [...fileList.value]);

			// 使用Promise.allSettled处理并行上传
			const uploadResults = await Promise.allSettled(
				files.map((file, i) => {
					const currentIndex = startIndex + i;

					return new Promise(async (resolve) => {
						try {
							const result = await uploadFilePromise(file.url);

							// 更新成功状态
							fileList.value[currentIndex] = {
								...fileList.value[currentIndex],
								status: 'success',
								message: '上传成功',
								data: result
							};

							// 确保传递给父组件的是完成的对象，不是Promise
							const completedFile = {
								...fileList.value[currentIndex]
							};
							emit('upload-complete', {
								file: completedFile,
								index: currentIndex
							});

							resolve(completedFile);
						} catch (error) {
							console.error(`文件 ${file.name} 上传失败:`, error);
							resolve(null);
						} finally {
							// 无论成功失败都触发更新
							emit('file-change', [...fileList.value]);
						}
					});
				})
			);

			// 处理上传结果统计
			const successCount = uploadResults.filter(r => r.status === 'fulfilled' && r.value).length;
			console.log(`上传完成: 成功 ${successCount} 个，失败 ${uploadResults.length - successCount} 个`);
		} catch (error) {
			console.error('处理上传时发生全局错误:', error);
			emit('upload-error', error);
		}
	};
	// const afterRead = async (event) => {
	// 	// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
	// 	const lists = [].concat(event.file);
	// 	let startIndex = fileList.value.length;

	// 	// 添加文件到列表，状态为上传中
	// 	lists.forEach((item) => {
	// 		fileList.value.push({
	// 			...item,
	// 			status: 'uploading',
	// 			message: '上传中'
	// 		});
	// 	});
	// 	emit('file-change', fileList.value)

	// 	// 逐个上传文件
	// 	for (let i = 0; i < lists.length; i++) {
	// 		const currentIndex = startIndex + i;
	// 		try {
	// 			// const result = await
	// 			uploadFilePromise(lists[i].url).then(result => {
	// 				// 更新文件状态为上传成功
	// 				fileList.value[currentIndex] = {
	// 					...fileList.value[currentIndex],
	// 					status: 'success',

	// 					data: result
	// 				};
	// 				emit('upload-complete', {
	// 					file: fileList.value[currentIndex],
	// 					index: currentIndex
	// 				});
	// 			});


	// 		} catch (error) {
	// 			// 更新文件状态为上传失败

	// 			console.error('上传失败:', error);
	// 		}
	// 	}
	// };

	// 文件上传函数
	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: '/undefined/exfile/file/single/upload', // 替换为你的实际接口地址
				filePath: url,
				name: 'file',
				formData: {},
				success: (res) => {
					try {
						const data = JSON.parse(res.data);
						resolve(data.data || data.url); // 根据你的接口返回结构调整
					} catch (e) {
						reject(new Error('解析响应数据失败'));
					}
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	};

	// 暴露方法给父组件
	defineExpose({
		fileList,
		getFileList: () => fileList.value,
		clearFiles: () => {
			fileList.value = [];
		}
	});
	// onMounted(() => {
	// 	console.log("props.initialFiles", props.initialFiles)
	// 	if (props.initialFiles.length > 0) {
	// 		fileList.value = props.initialFiles.map(file => ({
	// 			...file,
	// 			status: file.status || 'success',
	// 			message: file.message || ''
	// 		}));
	// 	}
	// })
	watch(() => props.initialFiles, (newFiles) => {
		newFiles.then(res => {
			if (res && res.length > 0) {
				fileList.value = res?.map(file => ({
					...file,
					status: file.status || 'success',
					message: file.message || ''
				}));
			}
		})

	}, {
		immediate: true,
		deep: true
	})
</script>

<style>
	/* 可以添加一些自定义样式 */
</style>